/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.games.esmi.ieat.indicatorrelations;

import com.vaadin.terminal.Sizeable;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.Tree;
import com.vaadin.ui.VerticalLayout;
import eu.games.esmi.ieat.indicatorrelations.data.ClusterMiner;
import eu.games.esmi.ieat.indicatorrelations.ui.DatePopupInputPrompt;
import eu.games.esmi.ieat.indicatorrelations.ui.NumericTextField;
import eu.games.esmi.ieat.indicatorvalues.IndicatorTreeGenerator;
import eu.games.esmi.ieat.indicatorvalues.data.EMF;
import it.polimi.games.epkb.entityClasses.StoredValues;
import it.polimi.games.epkb.manager.EPKBmanager;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Set;
import weka.core.Attribute;
import weka.core.Instance;

/**
 *
 * @author user
 */
public class ClusteringDesignTab extends Panel {

    public NumericTextField sampling = new NumericTextField("Sampling period (sec)", 30);
//    public DatePopupInputPrompt start = new DatePopupInputPrompt("Start time", new Date(new Date().getTime() - 500 * sampling.getNumber() * 1000));
//    public DatePopupInputPrompt end = new DatePopupInputPrompt("End time", new Date());
    public DatePopupInputPrompt start = new DatePopupInputPrompt("Start time", new GregorianCalendar(2012,5,12,17,0,0).getTime());
    public DatePopupInputPrompt end = new DatePopupInputPrompt("End time", new GregorianCalendar(2012,5,12,18,0,0).getTime());
    public NumericTextField clusters = new NumericTextField("Number of clusters", 2);
    public NumericTextField iterations = new NumericTextField("Maximum number of iterations", 500);
    public Tree indicatorTree = new IndicatorTreeGenerator().createTree(IndicatorTreeGenerator.INDICATOR_TREE);
    public TextArea indicatorsToClusterTextArea = new TextArea("Indicators to cluster");
    
    private String separator = "\n\r";
 
    public ClusteringDesignTab() {
        super();
        init();
    }
    
    public void init() {

        HorizontalLayout h = new HorizontalLayout();
        h.setSpacing(true);
        
        //HorizontalLayout h1 = new DragDropTableTree();
        HorizontalLayout h1 = new HorizontalLayout();
        h1.setSpacing(true);
        
            h1.addComponent(indicatorTree);
        
            Button addButton = new Button("Add");
            addButton.addListener(new Listener() {

                public void componentEvent(Event event) {
                //PROVA
                //Tabs.INSTANCE.correlationAnalysisTab.addCorrelationToTable(new Correlation("[PROVA] Sampling time", sampling.getNumber().toString()));
                    for (Object indicator : ((Set<Object>)indicatorTree.getValue()).toArray()) {
                        addToIndicatorsToCluster(indicator.toString());
                    }
                }
            });
            h1.addComponent(addButton);
            
            indicatorsToClusterTextArea.setHeight(320, Sizeable.UNITS_PIXELS);
            h1.addComponent(indicatorsToClusterTextArea);

            VerticalLayout v11 = new VerticalLayout();
            v11.setSpacing(true);

                Button deleteButton = new Button("Delete");
                deleteButton.addListener(new Listener() {
                    public void componentEvent(Event event) {
                        indicatorsToClusterTextArea.setValue("") ;
                    }
                });
                v11.addComponent(deleteButton);
                
                Button startButton = new Button("Start");
                startButton.addListener(new Listener() {
                    
                    public void componentEvent(Event event) {
                        
                        EPKBmanager epkb = new EPKBmanager(EMF.PU_NAME);
                        long startTime = start.getDatetime().getTime();
                        long endTime = end.getDatetime().getTime();
                        long samplingTime = sampling.getNumber().longValue() * 1000;
                        MainIndicatorRelations.getClusteringAnalysisTab().clearLegendOfZelda();
                        ClusterMiner miner = new ClusterMiner();
                        for(String indicator : ((String)(indicatorsToClusterTextArea.getValue())).split(separator)) {
                            System.out.println("Extracting values for " + indicator + "...");
                            List<String> colorList = new ArrayList<String>();
                            List<Long> delta = new ArrayList<Long>();
                            for (long t = startTime; t < endTime; t = t + samplingTime) {
                                StoredValues storedvalue = epkb.getIndicator(indicator.split("-")[0], indicator.split("-")[1], new Date(t));
                                colorList.add(storedvalue.getRed()?"red":(storedvalue.getYellow()?"yellow":"green"));
                                delta.add(storedvalue.getDefinitionTime().getTime() - t);
                            }
                            String[] colors = new String[colorList.size()];
                            for (int i = 0; i < colors.length; i++) {
                                colors[i] = colorList.get(i);
                            }
                            miner.load(indicator, colors);
                            System.out.println(colors.length + " values loaded.");
                        }
        
                        String clustersNumber = clusters.getNumber() + "";
                        String maxIterations = iterations.getNumber() + "";
        
                        String[] options = {
                            "-N",clustersNumber,
                            "-A","weka.core.EuclideanDistance",
                            "-R","first-last",
                            "-I",maxIterations,
                            "-S", "10"
                        };
        
                        //set options and mine clusters
                        miner.findClusters("SimpleKMeans", options);
                        
                        System.out.println(miner);
                        double[] clusteredInstances = miner.getClusteredInstances();
                        for (int i = 0; i < clusteredInstances.length; i++) {
                            System.out.println("["+i+"]: "+clusteredInstances[i]+"%");
                            MainIndicatorRelations.getClusteringAnalysisTab().addClusterToTable("Cluster #" + i, clusteredInstances[i]); 
                        }
                        weka.clusterers.SimpleKMeans kmeans = (weka.clusterers.SimpleKMeans)miner.getClusterer();
                        Enumeration data = kmeans.getClusterCentroids().enumerateInstances();
                        while (data.hasMoreElements()){
                            Instance k = (Instance)(data.nextElement());
                            Enumeration attributes = k.enumerateAttributes();
                            String s = "";
                            while (attributes.hasMoreElements()){
                                Attribute a = (Attribute)(attributes.nextElement());
                                s += a.name() + "; ";
                            }
                            System.out.println(s + " = " + k);
                            MainIndicatorRelations.getClusteringAnalysisTab().addGamesToLegenda(s, k.toString());
                                //MainIndicatorRelations.getClusteringAnalysisTab().addGamesToLegenda(indicators, data.nextElement());
                        }

                        getWindow().showNotification("Clustering data available");
                    }
                });
                v11.addComponent(startButton);

            h1.addComponent(v11);

        h.addComponent(h1);
        
        HorizontalLayout h2 = new HorizontalLayout();
            h2.setSpacing(true);
        
            VerticalLayout v21 = new VerticalLayout();
            v21.setSpacing(true);

                v21.addComponent(start);
                
                v21.addComponent(end);

                v21.addComponent(sampling);

            h2.addComponent(v21);
            
            VerticalLayout v22 = new VerticalLayout();
            v22.setSpacing(true);
            h2.addComponent(v22);
            
            VerticalLayout v23 = new VerticalLayout();
            v23.setSpacing(true);

                v23.addComponent(clusters);
                
                v23.addComponent(iterations);

            h2.addComponent(v23);
            
        h.addComponent(h2);
            
        this.addComponent(h);
    }
        
    private boolean hasDefinedAssociation(String indicator) {
        return indicatorsToClusterTextArea.getValue().toString().contains(indicator);
    }
    
    private void addToIndicatorsToCluster(String indicator) {
        if (!hasDefinedAssociation(indicator))
            indicatorsToClusterTextArea.setValue(indicatorsToClusterTextArea.getValue() + indicator + separator);
    }

}
